package com.playtruly.wanzhende2025

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.util.Log
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import java.io.ByteArrayOutputStream
import java.net.HttpURLConnection
import java.net.URL
import android.os.Handler
import android.os.Looper
import kotlin.concurrent.thread

/**
 * 🔥 微信分享助手类
 * 
 * 基于微信官方Android SDK实现，避免Flutter插件兼容性问题
 */
class WeChatShareHelper {
    companion object {
        private const val TAG = "WeChatShareHelper"
        private const val APP_ID = "wxe2b01f15994e9ba1"
        private lateinit var api: IWXAPI
        
        /**
         * 初始化微信API
         */
        fun initWeChatAPI(context: Context): Boolean {
            return try {
                Log.d(TAG, "🔥 开始初始化微信API...")
                api = WXAPIFactory.createWXAPI(context, APP_ID, true)
                val result = api.registerApp(APP_ID)
                Log.d(TAG, "✅ 微信API初始化${if (result) "成功" else "失败"}")
                result
            } catch (e: Exception) {
                Log.e(TAG, "❌ 微信API初始化异常: ${e.message}")
                false
            }
        }
        
        /**
         * 检查微信是否已安装
         */
        fun isWeChatInstalled(): Boolean {
            return try {
                if (!::api.isInitialized) {
                    Log.w(TAG, "⚠️ 微信API未初始化")
                    false
                } else {
                    val installed = api.isWXAppInstalled
                    Log.d(TAG, "📱 微信安装状态: $installed")
                    installed
                }
            } catch (e: Exception) {
                Log.e(TAG, "❌ 检查微信安装状态异常: ${e.message}")
                false
            }
        }
        
        /**
         * 分享网页到微信 - 异步版本，参考MyApplication2实现
         */
        fun shareToWeChat(
            title: String,
            description: String,
            webUrl: String,
            thumbUrl: String?,
            isTimeline: Boolean
        ): Boolean {
            return try {
                Log.d(TAG, "🔗 开始分享到微信...")
                Log.d(TAG, "📝 标题: $title")
                Log.d(TAG, "📝 描述: $description")  
                Log.d(TAG, "🌐 链接: $webUrl")
                Log.d(TAG, "🖼️ 缩略图: $thumbUrl")
                Log.d(TAG, "📍 场景: ${if (isTimeline) "朋友圈" else "好友"}")
                
                if (!::api.isInitialized) {
                    Log.e(TAG, "❌ 微信API未初始化")
                    return false
                }
                
                // 参数验证
                if (title.isEmpty() || webUrl.isEmpty()) {
                    Log.e(TAG, "❌ 标题或链接为空")
                    return false
                }
                
                // 🚀 强制异步处理缩略图下载和分享 - 绝不在主线程执行网络请求
                if (!thumbUrl.isNullOrBlank()) {
                    Log.d(TAG, "🌐 启动独立后台线程下载缩略图: $thumbUrl")
                    Log.d(TAG, "🔒 当前线程: ${Thread.currentThread().name}")
                    
                    // 在独立的后台线程中下载图片
                    Thread {
                        try {
                            Log.d(TAG, "🔥 网络下载线程: ${Thread.currentThread().name}")
                            
                            // 双重保护：再次确认不在主线程
                            if (Looper.myLooper() == Looper.getMainLooper()) {
                                Log.e(TAG, "❌ 致命错误：后台线程检测到主线程环境！")
                                throw IllegalStateException("网络下载不能在主线程执行")
                            }
                            
                            val downloadedThumb = downloadThumbnail(thumbUrl)
                            
                            // 在主线程中执行分享
                            Handler(Looper.getMainLooper()).post {
                                val thumbData = if (downloadedThumb != null && downloadedThumb.isNotEmpty()) {
                                    Log.d(TAG, "✅ 使用下载的缩略图: ${downloadedThumb.size}B")
                                    downloadedThumb
                                } else {
                                    Log.d(TAG, "⚠️ 下载失败，使用默认缩略图")
                                    createDefaultThumbnail()
                                }
                                
                                performWeChatShare(title, description, webUrl, thumbData, isTimeline)
                            }
                            
                        } catch (e: Exception) {
                            Log.e(TAG, "💥 后台下载缩略图异常: ${e.message}")
                            Log.e(TAG, "🔍 异常详情: ${e.stackTraceToString()}")
                            
                            // 发生异常时在主线程使用默认缩略图
                            Handler(Looper.getMainLooper()).post {
                                val defaultThumb = createDefaultThumbnail()
                                performWeChatShare(title, description, webUrl, defaultThumb, isTimeline)
                            }
                        }
                    }.start()
                } else {
                    // 无缩略图URL时直接使用默认缩略图
                    Log.d(TAG, "🎨 无缩略图URL，使用默认缩略图")
                    val defaultThumb = createDefaultThumbnail()
                    performWeChatShare(title, description, webUrl, defaultThumb, isTimeline)
                }
                
                true // 返回true表示开始分享流程
                
            } catch (e: Exception) {
                Log.e(TAG, "💥 微信分享异常: ${e.message}")
                false
            }
        }
        
        /**
         * 执行微信分享请求（在主线程中调用）
         */
        private fun performWeChatShare(
            title: String,
            description: String,
            webUrl: String,
            thumbData: ByteArray,
            isTimeline: Boolean
        ) {
            try {
                Log.d(TAG, "🎯 执行微信分享请求")
                
                // 创建网页对象
                val webpage = WXWebpageObject()
                webpage.webpageUrl = webUrl
                
                // 创建媒体消息
                val msg = WXMediaMessage()
                msg.mediaObject = webpage
                msg.title = if (title.length > 512) title.substring(0, 512) else title
                msg.description = if (description.length > 1024) description.substring(0, 1024) else description
                msg.thumbData = thumbData
                
                Log.d(TAG, "📏 缩略图大小: ${thumbData.size} bytes")
                
                // 创建分享请求
                val req = SendMessageToWX.Req()
                req.transaction = "webpage_${System.currentTimeMillis()}"
                req.message = msg
                req.scene = if (isTimeline) {
                    SendMessageToWX.Req.WXSceneTimeline
                } else {
                    SendMessageToWX.Req.WXSceneSession
                }
                
                // 发送请求
                val result = api.sendReq(req)
                Log.d(TAG, "${if (result) "✅" else "❌"} 微信分享请求${if (result) "成功" else "失败"}")
                
            } catch (e: Exception) {
                Log.e(TAG, "💥 执行微信分享请求异常: ${e.message}")
                Log.e(TAG, "🔍 异常详情: ${e.stackTraceToString()}")
            }
        }
        
        /**
         * 下载网络缩略图 - 改进版本，参考MyApplication2成功实现
         */
        private fun downloadThumbnail(thumbUrl: String): ByteArray? {
            return try {
                // 🔥 强制检查：确保不在主线程执行网络请求
                if (Looper.myLooper() == Looper.getMainLooper()) {
                    Log.e(TAG, "❌ 严重错误：downloadThumbnail在主线程被调用！")
                    throw IllegalStateException("网络请求不能在主线程执行")
                }
                
                Log.d(TAG, "🌐 开始下载缩略图: $thumbUrl")
                val url = URL(thumbUrl)
                val connection = url.openConnection() as HttpURLConnection
                
                // 🔧 改进：增加超时时间和设置User-Agent
                connection.connectTimeout = 10000 // 10秒连接超时
                connection.readTimeout = 15000    // 15秒读取超时
                connection.doInput = true
                connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Android)")
                connection.connect()
                
                val responseCode = connection.responseCode
                Log.d(TAG, "📡 图片下载响应码: $responseCode")
                
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    val inputStream = connection.inputStream
                    var bitmap = BitmapFactory.decodeStream(inputStream)
                    inputStream.close()
                    connection.disconnect()
                    
                    if (bitmap != null) {
                        Log.d(TAG, "📐 原始图片尺寸: ${bitmap.width}x${bitmap.height}")
                        
                        // 🔧 改进：检查图片大小并进行适当缩放
                        if (bitmap.width > 150 || bitmap.height > 150) {
                            bitmap = Bitmap.createScaledBitmap(bitmap, 150, 150, true)
                            Log.d(TAG, "📏 图片已缩放到: 150x150")
                        }
                        
                        val stream = ByteArrayOutputStream()
                        
                        // 🔧 改进：先尝试PNG格式，超过32KB再用JPEG
                        bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream)
                        var result = stream.toByteArray()
                        
                        // 确保不超过32KB
                        if (result.size > 32 * 1024) {
                            stream.reset()
                            bitmap.compress(Bitmap.CompressFormat.JPEG, 75, stream)
                            result = stream.toByteArray()
                            
                            // 如果还是太大，继续降低质量
                            if (result.size > 32 * 1024) {
                                stream.reset()
                                bitmap.compress(Bitmap.CompressFormat.JPEG, 50, stream)
                                result = stream.toByteArray()
                            }
                            
                            Log.d(TAG, "🗜️ 缩略图压缩完成")
                        }
                        
                        stream.close()
                        Log.d(TAG, "✅ 缩略图处理成功: ${result.size}B")
                        result
                        
                    } else {
                        Log.w(TAG, "⚠️ 无法解码图片")
                        connection.disconnect()
                        null
                    }
                } else {
                    Log.w(TAG, "⚠️ HTTP响应码: $responseCode")
                    connection.disconnect()
                    null
                }
            } catch (e: Exception) {
                Log.e(TAG, "❌ 下载缩略图失败: ${e.message}")
                Log.e(TAG, "🔍 异常详情: ${e.stackTraceToString()}")
                null
            }
        }
        
        /**
         * 创建默认缩略图 - 改进版本
         */
        private fun createDefaultThumbnail(): ByteArray {
            return try {
                Log.d(TAG, "🎨 创建默认缩略图")
                // 创建一个150x150的绿色缩略图
                val bitmap = Bitmap.createBitmap(150, 150, Bitmap.Config.RGB_565)
                bitmap.eraseColor(0xFF4CAF50.toInt()) // 绿色背景
                
                val stream = ByteArrayOutputStream()
                
                // 先尝试PNG格式
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream)
                var result = stream.toByteArray()
                
                // 确保不超过32KB
                if (result.size > 32 * 1024) {
                    stream.reset()
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 75, stream)
                    result = stream.toByteArray()
                    
                    // 如果还是太大，继续降低质量
                    if (result.size > 32 * 1024) {
                        stream.reset()
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 50, stream)
                        result = stream.toByteArray()
                    }
                }
                
                stream.close()
                bitmap.recycle() // 释放bitmap内存
                
                Log.d(TAG, "✅ 默认缩略图创建成功: ${result.size}B")
                result
                
            } catch (e: Exception) {
                Log.e(TAG, "❌ 创建默认缩略图失败: ${e.message}")
                Log.e(TAG, "🔍 异常详情: ${e.stackTraceToString()}")
                ByteArray(0)
            }
        }
        
        /**
         * 获取微信版本支持的API
         */
        fun getWXAppSupportAPI(): Int {
            return try {
                if (::api.isInitialized) {
                    api.wxAppSupportAPI
                } else {
                    0
                }
            } catch (e: Exception) {
                Log.e(TAG, "❌ 获取微信API版本失败: ${e.message}")
                0
            }
        }
    }
}
